package cn.edu.henu.team.base;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.edu.henu.team.utils.ActivityManagerUtils;

public abstract class BaseActivity extends AppCompatActivity {
    public Context mContext;
    protected Toast toast;
    protected static String TAG;
    private Unbinder mUnBinder;
    private Bundle savedInstanceState;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;

        mContext = this;
        // 设置 TAG
        TAG = this.getClass().getSimpleName();
        setContentView(initLayout());
        //注册 ButterKnife
        mUnBinder = ButterKnife.bind(this);
        initView();
        initData();
    }

    public Bundle getSavedInstanceState() {
        return savedInstanceState;
    }

    protected abstract int initLayout();
    protected abstract void initView();
    protected abstract void initData();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnBinder.unbind();
        ActivityManagerUtils.mActivities.remove(this); //销毁所有视图
    }

    // 实现在子线程中显示Toast
    protected void showToastInThread(Context context, String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
                toast.show();
            }
        });
    }

    protected void hideToast() {
        if (toast != null) {
            toast.cancel();
            toast = null;
        }
    }

    /*
     * 配置文件：向指定model中插入键值对
     */
    protected void insertVal(String model,String key, String val) {
        SharedPreferences sp = getSharedPreferences(model, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, val);
        editor.commit();
    }

    /*
     * 取值
     */
    protected String findByKey(String model,String key) {
        SharedPreferences sp = getSharedPreferences(model, MODE_PRIVATE);
        return sp.getString(key, "");
    }
}
